<?php

namespace App\GraphQL\Mutations\User;

use App\Models\Order;
use GraphQL\Type\Definition\ResolveInfo;
use Illuminate\Support\Carbon;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
use App\Jobs\CompleteOrderJob;
class ErrorReport
{
    /**
     * Return a value for the field.
     *
     * @param  null  $rootValue Usually contains the result returned from the parent field. In this case, it is always `null`.
     * @param  mixed[]  $args The arguments that were passed into the field.
     * @param  \Nuwave\Lighthouse\Support\Contracts\GraphQLContext  $context Arbitrary data that is shared between all fields of a single query.
     * @param  \GraphQL\Type\Definition\ResolveInfo  $resolveInfo Information about the query itself, such as the execution state, the field name, path to the field from the root, and more.
     * @return mixed
     */
    public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
    {
        
        $id = $args['id'];
        $data = $args['input'];
        $order = $this->validate($id,$data);
        //
        $order->using_time = Carbon::now()->toString();
        $order->end_using_time = Carbon::now()->addSeconds($order->time_length);
        $order->status = 'USING';
        $order->save();
        // 在结束后一分钟完成订单
        CompleteOrderJob::dispatch($order)->delay(Carbon::now()->addSeconds($order->time_length + 60));
        return [
            'status'=> '200',
            'message'=>'使用成功'
        ];
    }
    public function validate($id,$data){
        $old = Order::find($data);
        if($old){
            throw new \Exception('用户已经存在!');
        }
        if ($old->status === 'WAIT_PAY') {
            throw new \Exception('订单未支付!');
        }
        if ($old->status === 'COMPLETE') {
            throw new \Exception('订单已完成!');
        }
        if ($old->status === 'REFUND_COMPLETE') {
            throw new \Exception('订单已退款!');
        }
        if ($old->status === 'WAIT_REFUND') {
            throw new \Exception('订单正在退款!');
        }
        return $old;
    }
}
